const fs = require('fs')
const path = require('path')

function camelize(str) {
  let camelizeRE = /-(\w)/g
  return str.replace(camelizeRE, function (_, c) {
    return c ? c.toUpperCase() : ''
  })
}

function isJsFile(fileName) {
  return /\.js$/.test(fileName)
}

let tabBar = {}

const createPageJson = function (config, routerPath = '../src/pages-config/') {
  let config2 = config || {}
  const srcPath = path.resolve(__dirname, routerPath)
  const result = fs.readdirSync(srcPath) || []

  result.forEach((v) => {
    let nameArr = v.split('.')
    let name = camelize(nameArr[0])
    if (isJsFile(v)) {
      const route = require(routerPath + v)
      if (name === 'tabBar') {
        tabBar = route
      } else if (Array.isArray(config2)) {
        config2.push(route)
      } else {
        config2[name] = route
      }
    } else if (camelize(v) === 'subPackages') {
      let arr = createPageJson([], routerPath + v + '/')
      config2[name] = arr
    }
  })

  return config2
}

const configStr = JSON.stringify(createPageJson(), null, '  ') + '{{endjson}}'
const tabBarStr =
  !tabBar.list || tabBar.list.length < 2
    ? ''
    : JSON.stringify(tabBar, null, '  ')

const strJson = configStr.replace(
  /(}{{endjson}})/g,
  tabBarStr
    ? '	 // #ifndef H5 \n ,\n "tabBar": ' + tabBarStr + ' \n /* #endif  */\n}'
    : '\n}'
)

fs.writeFile(path.resolve(__dirname, '../src/pages.json'), strJson, (e) =>
  e ? console.error(e) : console.log('pages.json 配置文件更新成功')
)
